/*
 * XXX
 */

package edu.uhcl.csci4838.group3.view;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import edu.uhcl.csci4838.group3.R;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper.CursorCourse;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper.CursorCourseCategoryWeight;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper.CursorTask;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper.CursorTaskAlert;
import edu.uhcl.csci4838.group3.database.info.Course;
import edu.uhcl.csci4838.group3.database.info.CourseCategoryWeight;
import edu.uhcl.csci4838.group3.database.info.Task;
import edu.uhcl.csci4838.group3.database.info.TaskAlert;
import edu.uhcl.csci4838.group3.view.help.HelpActivity;
import edu.uhcl.csci4838.group3.widget.DateButton;
import edu.uhcl.csci4838.group3.widget.StateRelativeLayout;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnDismissListener;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.Toast;

/**
 * XXX
 * 
 * @author Chris Waguespack
 *
 */
public class EditTaskActivity extends Activity {

	/**
	 * XXX
	 * 
	 * @author Chris Waguespack
	 */
	private class CustomDateSetListener implements
			DatePickerDialog.OnDateSetListener {
		
		/**
		 * XXX
		 */
		private final DateButton dateButton;
		
		/**
		 * XXX
		 * 
		 * @param dateButton
		 *            XXX
		 */
		public CustomDateSetListener(final DateButton dateButton) {
			this.dateButton = dateButton;
		}
		
		/**
		 * XXX
		 * 
		 * @param view
		 *            XXX
		 * @param year
		 *            XXX
		 * @param monthOfYear
		 *            XXX
		 * @param dayOfMonth
		 *            XXX
		 */
		/* 
		 * (non-Javadoc)
		 * 
		 * @see android.app.DatePickerDialog.OnDateSetListener#onDateSet(android.widget.DatePicker, int, int, int)
		 */
		@Override
		public void onDateSet(final DatePicker view,
				final int year,
				final int monthOfYear,
				final int dayOfMonth) {
			this.dateButton.setYear(year);
			this.dateButton.setMonth(monthOfYear);
			this.dateButton.setDay(dayOfMonth);
		}
	}
	
	/**
	 * XXX
	 */
	private static final int DATE_DIALOG_ID = 0;
	
	/**
	 * The database helper object.
	 */
	private static BackpackEduDatabaseHelper dbHelper;
	
	/**
	 * The task cursor used to populate this form.
	 */
	private CursorTask taskCursor;
	
	/**
	 * The course id for this task.
	 */
	private long courseId;
	
	/**
	 * A list of deleted task alert ids.
	 */
	private List<Long> deletedTaskAlertIds;
	
	private static EditText inputTaskName;
	private static Spinner spinnerCategory;
	private static CheckBox cbCompleted;
	private static DateButton btnSelectDueDate;
	private static EditText inputReceivedGrade;
	private static EditText inputMaxGrade;
	private static EditText inputWeightOverride;
	private static LinearLayout layoutAlerts;
	
	/**
	 * XXX
	 * 
	 * @param view
	 *            XXX
	 */
	public void addAlertListItem(final View view) {
		this.getLayoutInflater()
				.inflate(R.layout.item_add_alert,
						EditTaskActivity.layoutAlerts);
	}
	
	/**
	 * XXX
	 * 
	 * @param view
	 *            XXX
	 */
	public void formCancel(final View view) {
		this.finish();
	}
	
	/**
	 * XXX
	 * 
	 * @param view
	 *            XXX
	 */
	public void formDone(final View view) {
		if (this.taskCursor == null) {
			// Add
			final String taskName = EditTaskActivity.inputTaskName.getText()
					.toString()
					.trim();
			if (taskName.length() == 0) {
				// Empty string
				Toast.makeText(this,
						"The task name cannot be empty!",
						Toast.LENGTH_LONG)
						.show();
				return;
			}
			
			// Check for existing task
			ContentValues criteria = new ContentValues();
			criteria.put(Course.ID, Long.valueOf(this.courseId));
			CursorCourse courseCursor = dbHelper.getCourse(criteria, null, true);
			
			CursorCourseCategoryWeight categoryCursor = (CursorCourseCategoryWeight) spinnerCategory.getSelectedItem();
			final String categoryName = categoryCursor.getColCategoryName();
			// XXX do I have to close this one?
			
			criteria = new ContentValues(4);
			criteria.put(Task.COURSE_ID, Long.valueOf(this.courseId));
			criteria.put(Task.SEMESTER_NAME, courseCursor.getColSemesterName());
			criteria.put(Task.CATEGORY_NAME, categoryName);
			criteria.put(Task.NAME,
					taskName);
			final CursorTask newTaskCursor = EditTaskActivity.dbHelper.getTask(criteria,
					null,
					true);
			if (newTaskCursor.getCount() != 0) {
				// The task name already exists
				Toast.makeText(this,
						"A task with that name already exists!",
						Toast.LENGTH_LONG)
						.show();
				return;
			}
			newTaskCursor.close();
			
			// Alerts
			final List<Integer> alerts = new ArrayList<Integer>(EditTaskActivity.layoutAlerts.getChildCount());
			for (int i = 0; i < EditTaskActivity.layoutAlerts.getChildCount(); ++i) {
				final View child = EditTaskActivity.layoutAlerts.getChildAt(i);
				if (child.getId() == R.id.item_add_alert) {
					int minutesBefore = 0;
					final String days = ((EditText) child.findViewById(R.id.editText_days)).getText()
							.toString()
							.trim();
					final String hours = ((EditText) child.findViewById(R.id.editText_hours)).getText()
							.toString()
							.trim();
					final String minutes = ((EditText) child.findViewById(R.id.editText_minutes)).getText()
							.toString()
							.trim();
					if (days.length() > 0
							|| hours.length() > 0
							|| minutes.length() > 0) {
						if (days.length() != 0) {
							minutesBefore += Integer.parseInt(days) * 1440;
						}
						if (hours.length() != 0) {
							minutesBefore += Integer.parseInt(hours) * 60;
						}
						if (minutes.length() != 0) {
							minutesBefore += Integer.parseInt(minutes);
						}
						
						for (final Integer minBefore : alerts) {
							if (minutesBefore == minBefore.intValue()) {
								Toast.makeText(this,
										"A duplicate alert exists!",
										Toast.LENGTH_LONG)
										.show();
								return;
							}
						}
						alerts.add(Integer.valueOf(minutesBefore));
					}
				}
			}
			
			// All good			
			criteria = new ContentValues();
			criteria.put(Task.IS_COMPLETED, Boolean.valueOf(cbCompleted.isChecked()));
			
			long dueDate = new GregorianCalendar(btnSelectDueDate.getYear(),
					btnSelectDueDate.getMonth(),
					btnSelectDueDate.getDay()).getTimeInMillis();
			criteria.put(Task.DATE_DUE, Long.valueOf(dueDate));
			
			final String receivedGrade = EditTaskActivity.inputReceivedGrade.getText()
					.toString()
					.trim();
			if (receivedGrade.length() > 0) {
				criteria.put(Task.RECEIVED_GRADE, Double.valueOf(receivedGrade));
			}
			
			final String maxGrade = EditTaskActivity.inputMaxGrade.getText()
					.toString()
					.trim();
			if (maxGrade.length() > 0) {
				criteria.put(Task.MAX_GRADE, Double.valueOf(maxGrade));
			}
			
			final String weightOverride = EditTaskActivity.inputWeightOverride.getText()
					.toString()
					.trim();
			if (weightOverride.length() > 0) {
				criteria.put(Task.WEIGHT_OVERRIDE, Double.valueOf(weightOverride));
			}
			
			EditTaskActivity.dbHelper.addTask(taskName, courseCursor.getColName(), courseCursor.getColSemesterName(), categoryName, criteria);
			for (Integer minutesBefore : alerts) {
				EditTaskActivity.dbHelper.addTaskAlert(taskName, courseCursor.getColName(), courseCursor.getColSemesterName(), categoryName, minutesBefore);
			}
			courseCursor.close();
		} else {
			// Edit
			final String taskName = EditTaskActivity.inputTaskName.getText()
					.toString()
					.trim();
			ContentValues criteria = new ContentValues();
			criteria.put(Course.ID, Long.valueOf(this.courseId));
			CursorCourse courseCursor = dbHelper.getCourse(criteria, null, true);
			ContentValues taskCriteria = new ContentValues(4);
			CursorCourseCategoryWeight categoryCursor = (CursorCourseCategoryWeight) spinnerCategory.getSelectedItem();
			final String categoryName = categoryCursor.getColCategoryName();
			// XXX do I have to close this one?
			if (!taskName.equals(this.taskCursor.getColName())
					|| !categoryName.equals(this.taskCursor.getColCategoryName())) {
				// Rename
				if (taskName.length() == 0) {
					// Empty string
					Toast.makeText(this,
							"The task name cannot be empty!",
							Toast.LENGTH_LONG)
							.show();
					return;
				}
				
				// Check for existing task
				Log.d("BackpackEDU", "" + courseId + " " + courseCursor.getColSemesterName() + " " + categoryName + " " + taskName);
				taskCriteria.put(Task.COURSE_ID, Long.valueOf(this.courseId));
				taskCriteria.put(Task.SEMESTER_NAME, courseCursor.getColSemesterName());
				taskCriteria.put(Task.CATEGORY_NAME, categoryName);
				taskCriteria.put(Task.NAME, taskName);
				final CursorTask newTaskCursor = EditTaskActivity.dbHelper.getTask(taskCriteria,
						null,
						true);
				if (newTaskCursor.getCount() != 0) {
					// The task name already exists
					Toast.makeText(this,
							"A task with that name in the specified category already exists!",
							Toast.LENGTH_LONG)
							.show();
					return;
				}
				newTaskCursor.close();
			}
			
			taskCriteria.put(Task.IS_COMPLETED, Boolean.valueOf(cbCompleted.isChecked()));
			
			long dueDate = new GregorianCalendar(btnSelectDueDate.getYear(),
					btnSelectDueDate.getMonth(),
					btnSelectDueDate.getDay()).getTimeInMillis();
			taskCriteria.put(Task.DATE_DUE, Long.valueOf(dueDate));
			
			final String receivedGrade = EditTaskActivity.inputReceivedGrade.getText()
					.toString()
					.trim();
			if (receivedGrade.length() > 0) {
				taskCriteria.put(Task.RECEIVED_GRADE, Double.valueOf(receivedGrade));
			}
			
			final String maxGrade = EditTaskActivity.inputMaxGrade.getText()
					.toString()
					.trim();
			if (maxGrade.length() > 0) {
				taskCriteria.put(Task.MAX_GRADE, Double.valueOf(maxGrade));
			}
			
			final String weightOverride = EditTaskActivity.inputWeightOverride.getText()
					.toString()
					.trim();
			if (weightOverride.length() > 0) {
				taskCriteria.put(Task.WEIGHT_OVERRIDE, Double.valueOf(weightOverride));
			}
			
			// Alerts
			final HashMap<Long, Integer> alerts = new HashMap<Long, Integer>();
			for (int i = 0; i < EditTaskActivity.layoutAlerts.getChildCount(); ++i) {
				final View child = EditTaskActivity.layoutAlerts.getChildAt(i);
				if (child.getId() == R.id.item_add_alert) {
					int minutesBefore = 0;
					final String days = ((EditText) child.findViewById(R.id.editText_days)).getText()
							.toString()
							.trim();
					final String hours = ((EditText) child.findViewById(R.id.editText_hours)).getText()
							.toString()
							.trim();
					final String minutes = ((EditText) child.findViewById(R.id.editText_minutes)).getText()
							.toString()
							.trim();
					if (days.length() > 0
							|| hours.length() > 0
							|| minutes.length() > 0) {
						if (days.length() != 0) {
							minutesBefore += Integer.parseInt(days) * 1440;
						}
						if (hours.length() != 0) {
							minutesBefore += Integer.parseInt(hours) * 60;
						}
						if (minutes.length() != 0) {
							minutesBefore += Integer.parseInt(minutes);
						}
						
						for (final Map.Entry<Long, Integer> entry : alerts.entrySet()) {
							if (minutesBefore == entry.getValue().intValue()) {
								Toast.makeText(this,
										"A duplicate alert exists!",
										Toast.LENGTH_LONG)
										.show();
								return;
							}
						}
						alerts.put(Long.valueOf(((StateRelativeLayout) child).getFieldId()),
								Integer.valueOf(minutesBefore));
					}
				}
			}
			
			// All good
			EditTaskActivity.dbHelper.editTask(this.taskCursor.getColId(),
					taskCriteria);
			
			// Deleted alerts
			for (final Long id : this.deletedTaskAlertIds) {
				EditTaskActivity.dbHelper.deleteTaskAlert(id.longValue());
			}
			
			// New and edited alerts
			for (final Map.Entry<Long, Integer> entry : alerts.entrySet()) {
				if (entry.getKey().longValue() == -1) {
					// New
					EditTaskActivity.dbHelper.addTaskAlert(taskName, courseCursor.getColName(), courseCursor.getColSemesterName(), categoryName, entry.getValue());
				} else {
					// Edit
					final ContentValues alertCriteria = new ContentValues(1);
					alertCriteria.put(TaskAlert.MINUTES_BEFORE,
							entry.getValue());
					EditTaskActivity.dbHelper.editTaskAlert(entry.getKey().longValue(),
							alertCriteria);
				}
			}
			courseCursor.close();
		}
		this.finish();
	}
	
	/**
	 * XXX
	 * 
	 * @param menu
	 *            XXX
	 * @return XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {
		this.getMenuInflater()
				.inflate(R.menu.options_edittask,
						menu);
		return true;
	}
	
	/**
	 * XXX
	 * 
	 * @param item
	 *            XXX
	 * @return XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		switch (item.getItemId()) {
			case R.id.menu_item_delete_task:
				this.showDeleteTaskDialog();
				return true;
			case R.id.menu_item_settings:
				this.startActivity(new Intent(this.getApplicationContext(),
						SettingsActivity.class));
				return true;
			case R.id.menu_item_about:
				this.startActivity(new Intent(this.getApplicationContext(),
						AboutActivity.class));
				return true;
			case R.id.menu_item_help:
				this.startActivity(new Intent(this.getApplicationContext(),
						HelpActivity.class));
				return true;
			default:
				Log.wtf("BackpackEDU",
						"Undefined options menu item.");
				return super.onOptionsItemSelected(item);
		}
	}
	
	/**
	 * XXX
	 * 
	 * @param menu
	 *            XXX
	 * @return XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onPrepareOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onPrepareOptionsMenu(final Menu menu) {
		final MenuItem item = menu.findItem(R.id.menu_item_delete_task);
		if (item != null) {
			// Don't show 'Delete task' if we are adding
			if (this.taskCursor == null) {
				item.setVisible(false);
			} else {
				item.setEnabled(true);
			}
		}
		
		return super.onPrepareOptionsMenu(menu);
	}
	
	/**
	 * XXX
	 * 
	 * @param view
	 *            XXX
	 */
	public void removeAlert(final View view) {
		final StateRelativeLayout layout = (StateRelativeLayout) view.getParent();
		if (layout.getFieldId() > -1) {
			// This isn't a new alert
			this.deletedTaskAlertIds.add(Long.valueOf(layout.getFieldId()));
		}
		((LinearLayout) view.getParent()
				.getParent()).removeView(layout);
	}
	
	/**
	 * XXX
	 * 
	 * @param view
	 *            XXX
	 */
	public void showDateDialog(final View view) {
		final Bundle bundle = new Bundle(1);
		bundle.putParcelable("dateButton",
				((DateButton) view));
		this.showDialog(EditTaskActivity.DATE_DIALOG_ID,
				bundle);
	}
	
	/**
	 * XXX
	 * 
	 * @param savedInstanceState
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		this.setContentView(R.layout.activity_addedit_task);
		
		// Get components
		EditTaskActivity.inputTaskName = (EditText) this.findViewById(R.id.editText_taskName);
		EditTaskActivity.spinnerCategory = (Spinner) this.findViewById(R.id.spinner_category);
		EditTaskActivity.cbCompleted = (CheckBox) this.findViewById(R.id.cb_completed);
		EditTaskActivity.btnSelectDueDate = (DateButton) this.findViewById(R.id.btn_select_dueDate);
		EditTaskActivity.inputReceivedGrade = (EditText) this.findViewById(R.id.editText_receivedGrade);
		EditTaskActivity.inputMaxGrade = (EditText) this.findViewById(R.id.editText_maxGrade);
		EditTaskActivity.inputWeightOverride = (EditText) this.findViewById(R.id.editText_weightOverride);
		EditTaskActivity.layoutAlerts = (LinearLayout) this.findViewById(R.id.layout_alerts);
		
		// Initialize the deleted list
		this.deletedTaskAlertIds = new ArrayList<Long>();
		
		// Calling intent
		final Intent callingIntent = this.getIntent();
		final long taskId = callingIntent.getLongExtra(this.getString(R.string.intent_extra_taskId),
				-1);
		this.courseId = callingIntent.getLongExtra(this.getString(R.string.intent_extra_courseId), -1);
		
		// Start the database helper
		EditTaskActivity.dbHelper = new BackpackEduDatabaseHelper(this);
		
		// Spinner
		ContentValues criteria = new ContentValues();
		criteria.put(CourseCategoryWeight.COURSE_ID,
				Long.valueOf(this.courseId));
		final CursorCourseCategoryWeight categoryCursor = dbHelper.getCourseCategoryWeight(criteria, new String[] { CourseCategoryWeight.CATEGORY_NAME }, true);
		this.startManagingCursor(categoryCursor);
		final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
				android.R.layout.simple_spinner_item,
				categoryCursor,
				new String[] { CourseCategoryWeight.CATEGORY_NAME },
				new int[] {	android.R.id.text1 });
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerCategory.setAdapter(adapter);
		
		// New if -1, or edit if not
		if (taskId == -1) {
			this.initForAdd();
		} else {
			this.initForEdit(taskId);
		}
	}
	
	/**
	 * XXX
	 * 
	 * @param id
	 *            XXX
	 * @param args
	 *            XXX
	 * @return XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateDialog(int, android.os.Bundle)
	 */
	@Override
	protected Dialog onCreateDialog(final int id,
			final Bundle args) {
		switch (id) {
			case DATE_DIALOG_ID:
				final DateButton dateButton = args.getParcelable("dateButton");
				final Dialog dialog = new DatePickerDialog(this,
						new CustomDateSetListener(dateButton),
						dateButton.getYear(),
						dateButton.getMonth(),
						dateButton.getDay());
				dialog.setOnDismissListener(new OnDismissListener() {
					
					/**
					 * XXX
					 * 
					 * @param dialog
					 *            XXX
					 */
					/* 
					 * (non-Javadoc)
					 * 
					 * @see android.content.DialogInterface.OnDismissListener#onDismiss(android.content.DialogInterface)
					 */
					@Override
					public void onDismiss(final DialogInterface dialog) {
						EditTaskActivity.this.removeDialog(EditTaskActivity.DATE_DIALOG_ID);
					}
				});
				return dialog;
			default:
				return null;
		}
	}
	
	/**
	 * XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		EditTaskActivity.dbHelper.close();
		super.onDestroy();
	}
	
	/**
	 * XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onRestart()
	 */
	@Override
	protected void onRestart() {
		super.onRestart();
		// TODO Q&D fix to get it working
		if (this.taskCursor != null) {
			this.taskCursor.moveToFirst();
		}
	}

	/**
	 * XXX
	 */
	private void initForAdd() {
		// Title
		this.setTitle("Add task");
		
		// Set done button text
		((Button) this.findViewById(R.id.btn_task_done)).setText("Add");
	}
	
	/**
	 * XXX
	 * 
	 * @param taskId
	 *            XXX
	 */
	private void initForEdit(final long taskId) {
		// Cursor
		ContentValues criteria = new ContentValues();
		criteria.put(Task.ID,
				Long.valueOf(taskId));
		this.taskCursor = EditTaskActivity.dbHelper.getTask(criteria,
				null,
				true);
		this.startManagingCursor(this.taskCursor);
		
		// Title
		this.setTitle("Edit task");
		
		// Set done button text
		((Button) this.findViewById(R.id.btn_task_done)).setText("Save");
		
		// Populate the fields
		EditTaskActivity.inputTaskName.setText(this.taskCursor.getColName());
		
		// Category spinner
		// TODO I should really use OnItemSelectedListener and store the result globally
		criteria = new ContentValues();
		criteria.put(CourseCategoryWeight.COURSE_ID,
				Long.valueOf(this.courseId));
		criteria.put(CourseCategoryWeight.CATEGORY_NAME,
				this.taskCursor.getColCategoryName());
		final CursorCourseCategoryWeight categoryCursor = dbHelper.getCourseCategoryWeight(criteria, new String[] { CourseCategoryWeight.CATEGORY_NAME }, true);
		this.startManagingCursor(categoryCursor);
		for (int i = 0; i < spinnerCategory.getCount(); ++i) {
			if (spinnerCategory.getItemIdAtPosition(i) == categoryCursor.getColId()) {
				spinnerCategory.setSelection(i);
				break;
			}
		}
		
		// Completed
		cbCompleted.setChecked(this.taskCursor.getColIsCompleted());
		
		// Due date
		if (this.taskCursor.getColDateDue() != null) {
			final Calendar cal = new GregorianCalendar();
			cal.setTimeInMillis(this.taskCursor.getColDateDue().longValue());
			btnSelectDueDate.setDay(cal.get(Calendar.DAY_OF_MONTH));
			btnSelectDueDate.setMonth(cal.get(Calendar.MONTH));
			btnSelectDueDate.setYear(cal.get(Calendar.YEAR));
		}
		
		// Grade and weight
		if (this.taskCursor.getColReceivedGrade() != null) {
			inputReceivedGrade.setText(this.taskCursor.getColReceivedGrade().toString());
		}
		if (this.taskCursor.getColMaxGrade() != null) {
			inputMaxGrade.setText(this.taskCursor.getColMaxGrade().toString());
		}
		if (this.taskCursor.getColWeightOverride() != null) {
			inputWeightOverride.setText(this.taskCursor.getColWeightOverride().toString());
		}
		
		// Alerts
		criteria = new ContentValues();
		criteria.put(TaskAlert.TASK_ID,
				Long.valueOf(taskId));
		final CursorTaskAlert taskAlertCursor = EditTaskActivity.dbHelper.getTaskAlert(criteria,
				new String[] { TaskAlert.MINUTES_BEFORE },
				true);
		for (int i = 0; i < taskAlertCursor.getCount(); ++i) {
			final StateRelativeLayout v = (StateRelativeLayout) this.getLayoutInflater()
					.inflate(R.layout.item_add_alert,
							null);
			v.setFieldId(taskAlertCursor.getColId());
			
			final int minutes = taskAlertCursor.getColMinutesBefore();
			
			// Days
			if (minutes >= 1440) {
				((EditText) v.findViewById(R.id.editText_days)).setText(Integer.valueOf(minutes / 1440).toString());
			} else {
				((EditText) v.findViewById(R.id.editText_days)).setText(Integer.valueOf(0).toString());
			}

			// Hours
			if (minutes >= 60) {
				((EditText) v.findViewById(R.id.editText_hours)).setText(Integer.valueOf((minutes % 1440) / 60).toString());
			} else {
				((EditText) v.findViewById(R.id.editText_hours)).setText(Integer.valueOf(0).toString());
			}
			
			// Minutes
			((EditText) v.findViewById(R.id.editText_minutes)).setText(Integer.valueOf((minutes % 1440) % 60).toString());
			
			EditTaskActivity.layoutAlerts.addView(v);
			taskAlertCursor.moveToNext();
		}
		taskAlertCursor.close();
	}
	
	/**
	 * XXX
	 */
	private void showDeleteTaskDialog() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.menu_title_delete_task)
				.setMessage("Are you sure you want to delete the task \""
						+ this.taskCursor.getColName()
						+ "\" ?")
				.setPositiveButton("Delete",
						new DialogInterface.OnClickListener() {
							
							@SuppressWarnings("synthetic-access")
							@Override
							public void onClick(final DialogInterface dialog,
									final int which) {
								EditTaskActivity.dbHelper.deleteTask(EditTaskActivity.this.taskCursor.getColId());
								EditTaskActivity.this.finish();
							}
						})
				.setNegativeButton(android.R.string.cancel,
						new CancelListener());
		final AlertDialog alert = builder.create();
		alert.show();
	}
}
